<?php
/**
 * Created by PhpStorm.
 * User: PHP
 * Date: 2018/1/19
 * Time: 14:10
 */
namespace app\index\model;

use think\exception\PDOException;
use think\Model;

class Member extends Model
{
    protected $autoWriteTimestamp = true;

    /**
     * 添加用户
     *
     * @param $param
     *
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author   [小码哥]
     */
    public function insertMember($param)
    {
        try{
            $result = $this->allowField(true)->save($param);
            if($result){
                $item = $this->where('openid', $param['openid'])->find();
                return ['code' => 200, 'data' => $item->toArray(), 'msg' => '登录成功'];
            }
            return ['code' => 0, 'data' => null, 'msg' => '登录失败'];
        }catch(PDOException $e){
            return ['code' => 0, 'data' => null, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 检测用户是否存在
     *
     * @param array $where
     *
     * @return array|false|\PDOStatement|string|Model
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author   [小码哥]
     */
    public function getItem($where = [])
    {
        return $this->where($where)->find();
    }

    /**
     * 更新用户资料
     *
     * @param        $param
     * @param string $field
     *
     * @return array
     * @author   [小码哥]
     */
    public function updateUser($param, $field = 'id')
    {
        try{
            $result = $this->allowField(true)->update($param, [$field => $param[$field]]);
            if($result){
                return ['code' => 200, 'data' => null, 'msg' => '成功'];
            }
            return ['code' => 0, 'data' => null, 'msg' => '失败'];
        }catch(PDOException $e){
            return ['code' => 0, 'data' => null, 'msg' => $e->getMessage()];
        }
    }
}